home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
cpphtp2
/
code.jar
/
code
/
ch21
/
fig21_03.txt
< prev
next >
Wrap
Text File
|
1998-02-27
|
1KB
|
40 lines
1 // Fig. 21.3: fig21_03.cpp
2 // Demonstrating the const_cast operator.
3 #include <iostream.h>
4
5 class ConstCastTest {
6 public:
7 void setNumber( int );
8 int getNumber() const;
9 void printNumber() const;
10 private:
11 int number;
12 };
13
14 void ConstCastTest::setNumber( int num ) { number = num; }
15
16 int ConstCastTest::getNumber() const { return number; }
17
18 void ConstCastTest::printNumber() const
19 {
20 cout << "\nNumber after modification: ";
21
22 // the expression number-- would generate compile error
23 // undo const-ness to allow modification
24 const_cast< ConstCastTest * >( this )->number--;
25
26 cout << number << endl;
27 }
28
29 int main()
30 {
31 ConstCastTest x;
32 x.setNumber( 8 ); // set private data number to 8
33
34 cout << "Initial value of number: " << x.getNumber();
35
36 x.printNumber();
37 return 0;
38 }
39 }